/* 具体路由流程查看asssets/1.png */
import Vue from 'vue'
import router from './router'
import store from './store/index'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
const whiteList = ['/user/login', '/404'] //白名单
NProgress.configure({
	showSpinner: false
})
/**
 * 自定义查找字段, 根据最后一级某个字段查找完整树(整个父类)
 * @param {*} val     要查找对比的值
 * @param {*} data    要查找的数据
 * @param {*} fKey    要查找对比的字段
 */
const recursiveTreeByLastLevel = (val, data, fKey = 'value') => {
	let rData = [];
	for (let i = 0, len = data.length; i < len; i++) {
		rData.push(data[i]);
		if (data[i].children && data[i].children.length > 0) {
			rData = rData.concat(recursiveTreeByLastLevel(val, data[i].children, fKey));
			if (rData.some(item => item[fKey] === val)) return rData;
		}
		if (data[i][fKey] === val) return rData;
		rData = [];
	}
	return rData;
}
router.beforeEach((to, from, next) => {
	NProgress.start() // start progress bar
	/* 判断 token 校验用户信息， */
	if (sessionStorage.getItem('access_token')) {
		/* 判断获取菜单 */
		if (!store.state.permission.hasGetMenu) {
			store.dispatch('GenerateRoutes')
				.then(() => {
					// next();
					// return
					router.addRoutes(store.getters.addRouters);

					if (store.getters.addRouters.length == 1) {
						/* 表示没有多的页面 */

					} else {
						/* 先判断跳转的页面中，是否再路由中。如果不在怎应该跳转到首页 */
						let redirectpath = from.query.redirect;
						console.log("重定向不雅"+JSON.stringify(redirectpath))
						console.log("to.path重定向不雅"+JSON.stringify(to.path))
						if (redirectpath && store.getters.addRouters && store.getters.addRouters.length >
							0) {
							if (!store.getters.addRouters.some(item => item.path == redirectpath)) {
								redirectpath = to.path
							}
						}
						/* 特别处理用户直接关闭浏览器访问/doExercise*/
						if(redirectpath&&redirectpath=='/doExercise'){
							redirectpath='/'
						}
						let redirect = decodeURIComponent(redirectpath || to.path)
						if (to.path === redirect) {
							// hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
							next({
								...to,
								replace: true
							})
						} else {
							// 跳转到目的路由
							next({
								path: redirect
							})
						}
					}

				})
		} else {
			next()
		}

	} else {
		if (whiteList.indexOf(to.path) !== -1) {
			// 在免登录白名单，直接进入
			next()
		} else {
			next({
				path: '/user/login',
				query: {
					redirect: to.fullPath
				}
			})
			NProgress.done()
		}
	}
})

router.afterEach((to, from, next) => {
	NProgress.done() // finish progress bar
	var routerList = recursiveTreeByLastLevel(to.name, store.state.permission.routers, 'name')
	store.commit('SET_CRUMBLIST', routerList) // 通过vuex缓存
})